using UnityEngine;
using UnityEditor;
using System.Collections;
using System.IO;
using System.Text;
using UnityEngine.SceneManagement;

public class ETSceneObj
{
    private static int StartIndex = 0;

    public static void Start()
    {
        StartIndex = 0;
    }
    public static void End()
    {
        StartIndex = 0;
    }


    public static string MeshToString(MeshFilter mf, Transform t)
    {
        Quaternion r = t.localRotation;

        int numVertices = 0;
        Mesh m = mf.sharedMesh;
        if (!m)
        {
            return "####Error####";
        }
        Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;

        StringBuilder sb = new StringBuilder();

        foreach (Vector3 vv in m.vertices)
        {
            Vector3 v = t.TransformPoint(vv);
            numVertices++;
            sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, -v.z));
        }
        sb.Append("\n");
        foreach (Vector3 nn in m.normals)
        {
            Vector3 v = r * nn;
            sb.Append(string.Format("vn {0} {1} {2}\n", -v.x, -v.y, v.z));
        }
        sb.Append("\n");
        foreach (Vector3 v in m.uv)
        {
            sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));
        }
        for (int material = 0; material < m.subMeshCount; material++)
        {
            sb.Append("\n");
            sb.Append("usemtl ").Append(mats[material].name).Append("\n");
            sb.Append("usemap ").Append(mats[material].name).Append("\n");

            int[] triangles = m.GetTriangles(material);
            for (int i = 0; i < triangles.Length; i += 3)
            {
                sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                    triangles[i] + 1 + StartIndex, triangles[i + 1] + 1 + StartIndex, triangles[i + 2] + 1 + StartIndex));
            }
        }

        StartIndex += numVertices;
        return sb.ToString();
    }
}

public class MyObjExporter : ScriptableObject
{
    [MenuItem("ETSceneObj/ForServer OBJ")]
    static void DoExportWSubmeshes()
    {
        DoExport(true);
    }

    [MenuItem("ETSceneObj/ForServer OBJ (No Submeshes)")]
    static void DoExportWOSubmeshes()
    {
        DoExport(false);
    }


    static void DoExport(bool makeSubmeshes)
    {
        if (UnityEngine.Object.FindObjectsOfType<Transform>().Length == 0)
        {
            Debug.Log("Didn't Export Any Meshes; Nothing was selected!");
            return;
        }
        string sceneName = SceneManager.GetActiveScene().name;
        string fileName = EditorUtility.SaveFilePanel("Export .obj file", "", sceneName, "obj");
        if(fileName == "")
        {
            return;
        }
        ETSceneObj.Start();

        StringBuilder meshString = new StringBuilder();

        meshString.Append("#" + sceneName + ".obj"
                            + "\n#" + System.DateTime.Now.ToLongDateString()
                            + "\n#" + System.DateTime.Now.ToLongTimeString()
                            + "\n#-------"
                            + "\n\n");

        Transform[] transform = UnityEngine.Object.FindObjectsOfType<Transform>();
        for (int i = 0; i < transform.Length; i++)
        {
            Vector3 originalPosition = transform[i].position;

            if (!makeSubmeshes)
            {
                meshString.Append("g ").Append(transform[i].name).Append("\n");
            }
            meshString.Append(processTransform(transform[i], makeSubmeshes));

            WriteToFile(meshString.ToString(), fileName);

            transform[i].position = originalPosition;
        }

        ETSceneObj.End();
        Debug.Log("Exported Mesh: " + fileName);
    }

    static string processTransform(Transform t, bool makeSubmeshes)
    {
        StringBuilder meshString = new StringBuilder();

        meshString.Append("#" + t.name
                        + "\n#-------"
                        + "\n");
        //多个mesh在这里区分，如果想同名合并就只写一个。要分开，就不能有重名。
        if (makeSubmeshes)
        {
            if (t.parent == null)
            {
                meshString.Append("g ").Append(t.name).Append(t.name).Append("\n");
            }
        }

        MeshFilter mf = t.GetComponent<MeshFilter>();
        if (mf)
        {
            meshString.Append(ETSceneObj.MeshToString(mf, t));
        }

        for (int i = 0; i < t.childCount; i++)
        {
            meshString.Append(processTransform(t.GetChild(i), makeSubmeshes));
        }
        return meshString.ToString();
    }

    static void WriteToFile(string s, string filename)
    {
        if(s == "" || filename == "")
        {
            return;
        }
        using (StreamWriter sw = new StreamWriter(filename))
        {
            sw.Write(s);
        }
    }
}